package com.squirrel.michale;

/**
 * @author guanhao 观浩
 * @version 1.0.0.0
 * @createTime 2023/2/21 10:10 PM
 * @company Michale Squirrel
 * @link
 * @description
 */
public class LeetCode0640_2 {

    public String solveEquationNew(String equation) {
        int xPerfix = 0;
        int constantPerfix = 0;
        int equalSymbol = 1;
        int lastSymbol = 0;

        char[] chars = equation.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] == '=') {
                if (lastSymbol < i) {
                    constantPerfix += Integer.valueOf(equation.substring(lastSymbol, i)) * equalSymbol;
                }
                equalSymbol = -1;
                lastSymbol = i + 1;
            } else if (chars[i] == 'x') {
                if (lastSymbol == i || chars[i - 1] == '+') {
                    xPerfix += equalSymbol;
                } else if (chars[i - 1] == '-') {
                    xPerfix -= equalSymbol;
                } else {
                    xPerfix += Integer.valueOf(equation.substring(lastSymbol, i)) * equalSymbol;
                }
                lastSymbol = i + 1;
            } else if (chars[i] == '+' || chars[i] == '-') {
                if (lastSymbol < i) {
                    constantPerfix += Integer.valueOf(equation.substring(lastSymbol, i)) * equalSymbol;
                }
                lastSymbol = i;
            }
        }
        if (lastSymbol < equation.length()) {
            constantPerfix += Integer.valueOf(equation.substring(lastSymbol)) * equalSymbol;
        }

        if (xPerfix == 0 && constantPerfix != 0) {
            return "No solution";
        }

        if (xPerfix == 0 && constantPerfix == 0) {
            return "Infinite solutions";
        }
        return "x=" + (-constantPerfix/xPerfix);
    }

    public static void main(String[] args) {
        LeetCode0640_2 leetCode0640 = new LeetCode0640_2();
//        System.out.println(leetCode0640.solveEquationNew("x+5-3+x=6+x-2"));
//        System.out.println(leetCode0640.solveEquationNew("x=x"));
//        System.out.println(leetCode0640.solveEquationNew("2x=x"));
        System.out.println(leetCode0640.solveEquationNew("x=x+2"));
//        System.out.println(leetCode0640.solveEquationNew("-x=-1"));


    }
}
